package edu.mapi.ir.viewer.comm;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


/**
 * @author ZP
 */
public class ViewerComms {
	private String serverHostname = "localhost";
	private InetAddress serverAddress = null;
	private int serverPort = 6000;
	//private int myPort = -1;
	private boolean initialized = false;
	private DatagramSocket socket;
	private String labXML, gridXML;
	
	public boolean sendToServer(String message) {
		return sendUDP(message, serverAddress, serverPort);
	}
	
	public boolean sendUDP(String message, InetAddress hostAddr, int port) {
		
		if (!initialized)
			initComms();
		
		if (!initialized)
			return false;
		
		byte[] buf = message.getBytes();
		DatagramPacket packet = new DatagramPacket(buf, buf.length, hostAddr, port);
		
		try {
			socket.send(packet);
		}
		catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private boolean initComms() {
		
		int pdiv = serverHostname.indexOf(":");
		if (pdiv != -1) {
			serverPort = Integer.valueOf(serverHostname.substring(pdiv+1)).intValue();
			serverHostname = serverHostname.substring(0,pdiv);
		}
		
		try {
            serverAddress = InetAddress.getByName(serverHostname);
            socket = new DatagramSocket();
            initialized = true;
		}
		catch(Exception e) {
			e.printStackTrace();		
		}
				
		return initialized;
	}
	
	private byte[] bufread = new byte[4096];
    
	public String receiveMessage() {
	    DatagramPacket packet = new DatagramPacket(bufread, bufread.length);
        
        try {
        	socket.setSoTimeout(2000);
        	socket.setReuseAddress(true);
        	socket.receive(packet);
        	
        	if (serverPort == 6000) {
        		serverPort = packet.getPort();        		
        	}
        	
        	return new String(packet.getData(), 0, packet.getLength()-1);
        }
        catch(Exception e) {
        	//e.printStackTrace();
        	return null;
        }        
	}
	
	public void connect(String hostname, int port) {
		this.serverHostname = hostname;
		initComms();
		sendToServer("<View/>\n");
		//System.out.println(receiveMessage());
		// i should parse this...
		receiveMessage();
		sendToServer("<LabReq/>\n");
		labXML = receiveMessage();
		sendToServer("<GridReq/>");
		gridXML = receiveMessage();				
	}
	
	public static void main(String[] args) throws Exception {
		ViewerComms comms = new ViewerComms();		
		comms.connect("localhost", 6000);
		
		comms.sendToServer("<Start/>");
		
		while (true) {
			//comms.sendToServer("<GridReq/>");
			System.out.println(comms.receiveMessage());
			
		}
	}

	public String getLabXML() {
		return labXML;
	}

	public String getGridXML() {
		return gridXML;
	}
}
